// 智能菜谱详情
import 'package:auto_route/auto_route.dart';
import 'package:casdon/app/config/env/env_provider.dart';
import 'package:casdon/app/config/theme/theme_extention.dart';
import 'package:casdon/app_providers.dart';
import 'package:casdon/build_gen/assets.gen.dart';
import 'package:casdon/common/service/tuya_service.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/gradient_button.dart';
import 'package:casdon/core/utils/toast_utils.dart';
import 'package:casdon/core/widgets/common_bottom_sheet.dart';
import 'package:casdon/modules/lifeCircle/utils/count_format_utils.dart';
import 'package:casdon/modules/login/ui/widgets/web_page.dart';
import 'package:casdon/modules/me/ui/widgets/icon_label_button.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_detail_info_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_favorite_operate_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_like_operate_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_products_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_put_brower_notifier.dart';
import 'package:casdon/modules/recipe/data/api/recipe_detail_info_api.dart';

import 'package:casdon/modules/recipe/ui/widgets/cooking_setting_content.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:tuya_home_sdk_flutter/tuya_home_sdk_flutter.dart';
@RoutePage()
class RecipeDetailScreen extends ConsumerStatefulWidget {
  final String recipeId;
  final String? devId;
  final String title;
  final int collectNum = 0;
  final int likeNum = 0;
  final bool isSmart;
  final bool? isMiffy;

  const RecipeDetailScreen({
    super.key,
    required this.recipeId,
    this.devId,
    this.isMiffy,
    required this.title,
    required this.isSmart,
  });

  @override
  ConsumerState<RecipeDetailScreen> createState() {
    return _RecipeDetailState();
  }
}

class _RecipeDetailState extends ConsumerState<RecipeDetailScreen> {
  late int _collectNum;
  late int _likeNum;
  bool _isLikeRequesting = false;
  bool _isCollectRequesting = false;

  ProviderSubscription<ResponseRecipeDetailApi?>? _detailSubscription;

  Future<Uint8List?> _loadShareThumb() async {
    try {
      final data = await rootBundle.load(Assets.images.appAbout.path);
      return data.buffer.asUint8List();
    } catch (_) {
      return null;
    }
  }

  @override
  void initState() {
    super.initState();
    _collectNum = widget.collectNum;
    _likeNum = widget.likeNum;
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        ref
            .read(recipeDetailProvider.notifier)
            .getRecipeDetail(widget.recipeId);
      }
    });
    _detailSubscription = ref.listenManual<ResponseRecipeDetailApi?>(
      recipeDetailProvider,
      (previous, next) {
        if (!mounted || next == null) return;
        final parsedLikes = int.tryParse(next.likes ?? '') ?? 0;
        final parsedCollect = int.tryParse(next.collection ?? '') ?? 0;
        final safeLikes = parsedLikes < 0 ? 0 : parsedLikes;
        final safeCollect = parsedCollect < 0 ? 0 : parsedCollect;
        if (_likeNum != safeLikes || _collectNum != safeCollect) {
          setState(() {
            _likeNum = safeLikes;
            _collectNum = safeCollect;
          });
        }
      },
    );
  }

  @override
  void dispose() {
    _detailSubscription?.close();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final productsState = ref.watch(
      recipeCanUseProductsProvider(widget.recipeId),
    );
    final _ = ref.watch(recipePutBrowerAsyProvier(widget.recipeId));
    // 监听点赞/收藏状态，保持对应的 StateNotifier 存活，避免 dispose 后仍被调用
    final likeState = ref.watch(recipeLikeOperateProvider(widget.recipeId));
    final collectState = ref.watch(
      recipeFavoriteOperateProvider(widget.recipeId),
    );

    final state = ref.watch(recipeDetailProvider);
    final url =
        "${getProvider(environmentProvider).recipe_web_url}${Uri.encodeComponent(widget.recipeId)}&t=${DateTime.now().millisecondsSinceEpoch}";
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(
        title: widget.title,
        backgroundColor: Colors.transparent,
        rightActions: [
          IconButton(
            icon: const Icon(Icons.ios_share_sharp, color: Colors.black87),
            iconSize: 24.w,
            onPressed: () async {
              final thumb = await _loadShareThumb();
              await fluwx.Fluwx().share(
                fluwx.WeChatShareWebPageModel(
                  url,
                  title: widget.title,
                  description: '分享自凯度生活家',
                  scene: fluwx.WeChatScene.session,
                  thumbData: thumb,
                ),
              );
            },
            tooltip: '分享',
          ),
        ],
      ),
      body: SafeArea(
        child: Column(
          children: [
            Expanded(
              child: WebPage(url: url, title: "", isFullScreen: false),
            ),
            Container(
              decoration: BoxDecoration(
                color: Colors.white,
                border: const Border(
                  top: BorderSide(color: Color(0xFFE5E5E5), width: 0.5),
                ),
              ),
              child: Column(
                children: [
                  SizedBox(height: 12.h),
                  Row(
                    children: [
                      SizedBox(width: 21.w),
                      // 左半部分
                      Expanded(
                        child: Row(
                          children: [
                            Expanded(
                              child: IconLabelButton(
                                imagePath: likeState
                                    ? Assets.images.icZaned.path
                                    : Assets.images.icZan.path,
                                layoutDirection: Axis.horizontal,
                                label: CountFormatUtils.formatCount(_likeNum),
                                onTap: () =>
                                    _handleZanTap(context, ref, likeState),
                              ),
                            ),
                            Expanded(
                              child: IconLabelButton(
                                imagePath: collectState
                                    ? Assets.images.icCollected.path
                                    : Assets.images.icCollect.path,
                                layoutDirection: Axis.horizontal,
                                label: _collectNum.toString(),
                                onTap: () => _handleCollectTap(
                                  context,
                                  ref,
                                  collectState,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),

                      // ✅ 右半部分
                      Expanded(
                        child: widget.isSmart
                            ? GradientButton(
                                height: 40.h,
                                enabled:
                                    productsState.devList.isNotEmpty ||
                                    widget.devId != null,
                                text:
                                    productsState.devList.isNotEmpty ||
                                        widget.devId != null
                                    ? "一键烹饪"
                                    : "未发现可用设备",
                                textStyle: context.textTheme.headlineLarge!
                                    .copyWith(color: Colors.white),
                                onPressed: () => _handleOneKeyTap(context, ref),
                              )
                            : const SizedBox(), // ✅ 不显示时用占位
                      ),

                      SizedBox(width: 12.w),
                    ],
                  ),

                  SizedBox(height: 12.h),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _handleZanTap(BuildContext context, WidgetRef ref, bool isSelect) async {
    if (_isLikeRequesting) {
      return;
    }
    _isLikeRequesting = true;
    var ret = false;
    try {
      if (isSelect == true) {
        ret = await ref
            .read(recipeLikeOperateProvider(widget.recipeId).notifier)
            .delLike(widget.recipeId);
        if (ret) {
          setState(() {
            _likeNum = (_likeNum - 1).clamp(0, 999999);
          });
        }
      } else {
        ret = await ref
            .read(recipeLikeOperateProvider(widget.recipeId).notifier)
            .addLike(widget.recipeId);
        if (ret) {
          setState(() {
            _likeNum++;
          });
        }
      }

      // final _ = ref.refresh(recipeUserInfoProvider(widget.recipeId));
    } finally {
      _isLikeRequesting = false;
    }
  }

  void _handleCollectTap(
    BuildContext context,
    WidgetRef ref,
    bool isSelect,
  ) async {
    if (_isCollectRequesting) {
      return;
    }
    _isCollectRequesting = true;
    var ret = false;
    try {
      if (isSelect == true) {
        ret = await ref
            .read(recipeFavoriteOperateProvider(widget.recipeId).notifier)
            .delFavorite(widget.recipeId);
        if (ret) {
          setState(() {
            _collectNum = (_collectNum - 1).clamp(0, 999999);
          });
          ToastUtil.show("取消收藏");
        }
      } else {
        ret = await ref
            .read(recipeFavoriteOperateProvider(widget.recipeId).notifier)
            .addFavorite(widget.recipeId);
        if (ret) {
          setState(() {
            _collectNum++;
          });
          ToastUtil.show("收藏成功");
        }
      }
    } finally {
      _isCollectRequesting = false;
    }
  }

  void _handleOneKeyTap(BuildContext context, WidgetRef ref) {
    CommonBottomSheet.show(
      context,
      child: CookingSettingContent(
        recipeId: widget.recipeId,
        devId: widget.devId,
        isMiffy: widget.isMiffy ?? false,
        onConfirm: (model) => _onStartCookCompleted(context, ref, model),
      ),
    );
  }

  // 一键烹饪点击后，进入面板
  void _onStartCookCompleted(
    BuildContext context,
    WidgetRef ref,
    ThingSmartDeviceModel model,
  ) {
    TuyaService().gotoPanel(
      deviceId: model.devId ?? "",
      pid: model.productId ?? "",
      fromType: PanelFromType.recipe_cook,
    );
    WidgetsBinding.instance.addPostFrameCallback((_) {});
  }
}
